package org.jbase.common.utils.message;

import java.io.Serializable;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * 封装消费者调用接口返回信息<br/>
 * 如果不够用自己添加 Created by ADon on 2016/7/22.
 */
public class Message<T> implements Serializable {

	private static final long serialVersionUID = 403590390097622048L;

	// 是否成功
	private boolean success;

	// 消息 返回MessageCode中的说明
	private String msg;

	// 消息状态码 返回MessageCode中的状态码
	private String code;

	// 数据
	private T data;

	public Message<T> setResultData(T data) {
		this.data = data;
		return this;
	}

	public Message<T> SetMessageCode(MessageCode messageCode) {
		this.msg = messageCode.getMsg();
		this.code = messageCode.getCode();
		return this;
	}

	/**
	 * 生产成功信息
	 *
	 * @return Message
	 */
	@SuppressWarnings("rawtypes")
	public static Message fireSuccess() {
		Message<?> message = new Message();
		message.setSuccess(true);
		message.setCode(MessageCode.SUCCESS.getCode());
		message.setMsg(MessageCode.SUCCESS.getMsg());
		return message;
	}

	/**
	 * 生产失败信息
	 *
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static Message fireFail() {
		Message<?> message = new Message();
		message.setSuccess(false);
		message.setCode(MessageCode.FAIL.getCode());
		message.setMsg(MessageCode.FAIL.getMsg());
		message.setData(null);
		return message;
	}

	public boolean getSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public T getData() {
		return data;
	}

	public void setData(T data) {
		this.data = data;
	}

	public static String jsonSuccess() {
		return JSON.toJSONString(fireSuccess());
	}

	public static String jsonFail() {
		return JSON.toJSONString(fireFail());
	}

	public static String json(Message<?> mess) {
		return JSON.toJSONStringWithDateFormat(mess, "yyyy-MM-dd hh:mm:ss", SerializerFeature.WriteMapNullValue);
	}

	public static String jsonData(Message<?> mess) {
		return JSON.toJSONStringWithDateFormat(mess.getData(), "yyyy-MM-dd hh:mm:ss",
				SerializerFeature.WriteMapNullValue);
	}

	public static String jsonObj(Object obj) {
		return JSON.toJSONStringWithDateFormat(obj, "yyyy-MM-dd hh:mm:ss", SerializerFeature.WriteMapNullValue);
	}

	@SuppressWarnings("unchecked")
	public static String jsonMessage(Object obj) {
		Message<Object> mess = fireSuccess();
		mess.setData(obj);
		return json(mess);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Message fail(Message mess, String code, String msg) {
		mess.setSuccess(false);
		mess.setCode(code);
		mess.setMsg(msg);
		mess.setData(null);
		return mess;
	}
}
